package com.gszkc.controller.admin;


import com.gszkc.dto.DishDTO;
import com.gszkc.dto.DishPageQueryDTO;
import com.gszkc.entity.Dish;
import com.gszkc.result.PageResult;
import com.gszkc.result.Result;
import com.gszkc.service.DishService;
import com.gszkc.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("adminDishController")
@Slf4j
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    @ApiOperation("菜品分页查询")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO){
        log.info("菜品分页查询：{}",dishPageQueryDTO);
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品：{}",dishDTO);
        dishService.saveWithFlavor(dishDTO);

        //删除缓存数据
        CleanCache("dish_" + dishDTO.getCategoryId());
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("菜品批量删除")
    public Result delete(@RequestParam List<Long> ids){
        log.info("批量删除菜品id:{}",ids);
        dishService.deleteBatch(ids);

        //清理缓存数据
        CleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询菜品和口味(回显)")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("根据id查询菜品和口味信息：{}",id);
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation("修改菜品和口味信息")
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品和口味信息：{}",dishDTO);
        dishService.updateWithFlavor(dishDTO);

        //清理缓存数据
        CleanCache("dish_*");
        return Result.success();
    }

    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售停售")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("菜品起售停售:{},{}",status,id);
        dishService.startOrStop(status,id);

        //清理缓存数据
        CleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类ID查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        log.info("根据分类ID查询菜品:分类ID{}",categoryId);
        List<Dish> dishList = dishService.list(categoryId);
        return Result.success(dishList);
    }

    private void CleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
